<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="shop.js"></script>
    <script>

        function $(id) {
            return document.getElementById(id);
        }

        window.onload = function () {
            showShopInfo();
        }

        /**显示购物车信息*/
        function showShopInfo() {
            let str = "";
            var allPrice = 0;
            shopArray.forEach(n => {
                str += `<tr><td>${n.pcode}</td>
                         <td>${n.pname}</td>
                         <td>${n.price}</td>
                         <td><input type="number" id="num" min="1" value="${n.num}" onblur="changeNum(${n.pcode},this.value)"></td>
                         <td>${n.price * n.num}</td>
                         <td><input type="button" value="移除商品" onclick="del(${n.pcode})"></td></tr>`;
                allPrice += n.price * n.num;
            });
            $("data").innerHTML = str;
            $("all").innerHTML = allPrice;
        }

        /**
         * 改变购买数量
         * @param code 要修改数量的商品的编号
         */
        function changeNum(code, num) {
            //找到要修改数量的对象
            let obj = shopArray.find(n => n.pcode == code);
            // obj.num = $("num").value;//问题在全部都会变成第一个数字框的数字
            obj.num = num;
            showShopInfo();
        }

        function del(code) {
            //找到指定编号对应商品的下标
            let index = shopArray.findIndex(n => n.pcode == code);
            shopArray.splice(index, 1);
            showShopInfo();
        }

    </script>
</head>
<body>
<table border="1" width="60%" cellspacing="0">
    <thead>
    <tr>
        <th>商品编号</th>
        <th>商品名称</th>
        <th>单价</th>
        <th>购买数量</th>
        <th>单项总价</th>
        <th>操作</th>
    </tr>
    </thead>
    <tbody id="data"></tbody>
</table>
购物车总价：<span id="all"></span>
</body>
</html>